<template>
  <div class="detail" v-if="detail">
    <!-- 主图轮播 -->
    <van-swipe :autoplay="3000">
      <van-swipe-item v-for="photo in detail.photo" :key="photo.id">
        <img v-lazy="photo.url" style="width: 100%;" />
      </van-swipe-item>
    </van-swipe>
    <!-- 标题、描述、价格等渲染 -->
    <div class="desc">
      <div class="title">
        <van-tag plain v-if="detail.isFreePostage" color="#f00">包邮</van-tag>
        {{ detail.title }}
      </div>
      <div class="price-container">
        <span class="price">￥{{ detail.price | money }}</span>
        <span class="origin-price">{{ detail.originPrice | money }}</span>
      </div>
      <div class="sale-num">
        月销量: {{ detail.saleNum }}
      </div>
    </div>

    <!-- 分割线 -->
    <van-divider>商品图文详情</van-divider>

    <!-- 图文详情 -->
    <div class="content">
      <img
        v-for="content in detail.descContentList"
        :key="content.photo.id"
        v-lazy="content.photo.url"
      />
    </div>

    <!-- 商品导航 -->
    <van-goods-action>
      <van-goods-action-icon icon="chat-o" text="客服" dot />
      <van-goods-action-icon icon="cart-o" text="购物车"  badge="0"  @click="$router.push('/cart')"/>
      <van-goods-action-button
        type="warning"
        text="加入购物车"
        @click="handleAddToCart"
      />
      <van-goods-action-button type="danger" text="立即购买" />
    </van-goods-action>
  </div>
</template>

<script>
import { getDetail } from '@/api/detail'
export default {
  name: 'Detail',
  data() {
    return {
      detail: null,
    }
  },
  async created() {
    // console.log('商品id:', this.$route.params.id)
    // 根据 id 查询出商品详情数据
    const { detail } = await getDetail(this.$route.params.id)
    this.detail = detail
  },
  methods: {
    /**
     * 加入购物车
     */
    handleAddToCart() {
      // 构建当前选购的商品对象
      const currentProduct = {
        id: this.detail.id,
        image: this.detail.image,
        title: this.detail.title,
        price: this.detail.price,
      }
      // 加入购物车，更新 vuex store 中的状态数据
      this.$store.dispatch('cart/addToCartAsync', currentProduct)
      // 提示
      this.$toast({
        type: 'success',
        message: '加入成功',
      })
    },
  },
}
</script>

<style lang="less" scoped>
  .detail {
    .desc {
      margin: 5px;
      .title {
        font-size: 16px;
        font-weight: 700;
        background: white;
        color: #333333;
        height: 70px;
      }
      van-tag{
        width: 150px;
      }

      .price {
        color: #f00;
        font-size: 16px;
        font-weight: 700;
      }

      .origin-price {
        color: #ccc;
        font-size: 12px;
        text-decoration: line-through;
        margin: 0 12px;
      }
      .sale-num {
        text-align: right;
        color: #ccc;
      }
    }
    .content {
      img {
        width: 100%;
        display: block;
      }
    }
  }
</style>
